package cn.swpu.blog.service.impl;

import cn.swpu.blog.dao.CategoryMapper;
import cn.swpu.blog.entity.Category;
import cn.swpu.blog.exception.CategoryNotFoundException;
import cn.swpu.blog.service.ICategoryService;
import cn.swpu.blog.vo.ResponseVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author 冰翔
 * @Date Created in 3:14 下午 2020/12/11
 */
@Service
public class CategoryServiceImpl implements ICategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public ResponseVo<Map<String, String>> queryCategoryById(Integer categoryId) {

        Category category = categoryMapper.selectByPrimaryKey(categoryId);

        //没有找到标签，抛出异常，统一异常处理
        if (category == null) {
            throw new CategoryNotFoundException("类别Id="+categoryId);
        }

        Map<String, String> map = new HashMap<>(1);
        map.put("category", category.getCategory());

        return ResponseVo.success(map);
    }

    @Override
    public ResponseVo<List<Category>> queryAllCategory() {

        List<Category> categoryList = categoryMapper.selectAll();
        return ResponseVo.success(categoryList);
    }

    @Override
    public ResponseVo<Map<String, Integer>> createCategory(String category) {
        Category record = new Category();
        record.setCategory(category);
        categoryMapper.insert(record);

        Map<String, Integer> map = new HashMap<>(1);
        map.put("categoryId", record.getCategoryId());
        return ResponseVo.success(map);
    }

    @Override
    public ResponseVo<Category> deleteCategory(Integer categoryId) {

        Category category = categoryMapper.selectByPrimaryKey(categoryId);
        if (category == null){
            throw new CategoryNotFoundException("类别ID不正确");
        }
        categoryMapper.deleteByPrimaryKey(categoryId);
        return ResponseVo.success(category);
    }

    @Override
    public ResponseVo<Category> updateCategory(Category category) {
        int result = categoryMapper.updateByPrimaryKey(category);

        if (result != 1){
            throw new CategoryNotFoundException("类别ID不正确");
        }
        Category categoryUpdated = categoryMapper.selectByPrimaryKey(category.getCategoryId());
        return ResponseVo.success(categoryUpdated);
    }
}
